package com.harleyquinn.gulimall.product.web;

import com.harleyquinn.gulimall.product.entity.CategoryEntity;
import com.harleyquinn.gulimall.product.service.CategoryService;
import com.harleyquinn.gulimall.product.vo.Catelog2Vo;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Description:
 * @Created: harleyquinn
 * @author: 哈莉·奎茵
 * @createTime: 2020-06-08 14:14
 **/

@Controller
public class IndexController {

    @Resource
    private CategoryService categoryService;

    @Autowired
    private RedissonClient redisson;
//
//    @Autowired
//    private StringRedisTemplate stringRedisTemplate;

    @GetMapping(value = {"/","index.html"})
    private String indexPage(Model model) {

        //1、查出所有的一级分类
        List<CategoryEntity> categoryEntities = categoryService.getLevel1Categorys();
        model.addAttribute("categories",categoryEntities);

        return "index";
    }


    //index/json/catalog.json
    @GetMapping(value = "/index/catalog.json")
    @ResponseBody
    public Map<String, List<Catelog2Vo>> getCatalogJson() {

        Map<String, List<Catelog2Vo>> catalogJson = categoryService.getCatalogJson();

        return catalogJson;

    }

    @ResponseBody
    @GetMapping("/hello")
    public String hello() {
        //1、获取一把锁，只要锁的名字一样就是同一把锁
        RLock myLock = redisson.getLock("myLock");
        //2、加锁
        //myLock.lock(); //阻塞式等待，过期时间默认30s
        myLock.lock(10,TimeUnit.SECONDS);//设置自动过期时间，则不会自动续期
        //锁的自动续期，如果业务执行时间超长，加锁期间会自动给锁续期30s
            //1、不用担心业务时间超长，锁过期
            //2、加锁的业务逻辑只要运行完成，就不会再自动续期，到期后锁会自动删除，不存在死锁问题

        try {
            System.out.println("加锁成功。执行业务");
        } finally {
            //3、加锁
           myLock.unlock();
        }
        return "hello";
    }
}
